/**
 * 加载提示拦截器
 * @author xuda-21609
 * @date 2020/2/10
 */
import {Toast} from "vant";
// import store from "../../store";

// 返回失败结果处理-提示信息
const RESPONSE_ERR_TEXT = "请求失败，请联系管理员！";
// 返回成功结果失败-提示信息
const RESPONSE_MSG_TEXT = "请求失败，返回信息有误！请联系管理员！";
const REQUEST_TIMEOUT_TEXT = "请求超时";
const CONNECT_FAIL_TEXT = "服务器连接失败";

// toast持续时间
const DURING_TIME = 2000;

let toast;
let timer = null;

function clearToast() {
    if (timer) clearTimeout(timer);
    Toast.clear();
}

/**
 * 请求加载效果拦截器
 * @param config
 */
const loadRequestSuccess = (config) =>{
    if (config && config.showModal) {
        clearTimeout(timer);
    }
    toast = Toast.loading({
        duration: 0,
        forbidClick: true,
        loadingType: "spinner",
        message: "加载中"
    });
    timer = setTimeout(() => {
        clearTimeout(timer);
        toast.message = REQUEST_TIMEOUT_TEXT;
        setTimeout(() => Toast.clear(), DURING_TIME);
    }, DURING_TIME * 10)
    return config
}

/**
 * 请求错误处理
 * @param error
 */
const loadRequestError = (error) => {
    clearToast();
    return Promise.reject(error);
}

/**
 * 返回成功结果处理
 * @param config
 */
const loadResponseSuccess = (response) => {
    if (response.data && response.status !== 200) {
        // 接口未返回正确结果，弹出组件
        toast.message = !response.data.message || response.data.message.length === 0 ? RESPONSE_MSG_TEXT : response.data.message;
        toast.icon = "fail";
        setTimeout(() => {
            clearToast()
        }, DURING_TIME);
        return Promise.reject(response.data.message);
    }

    clearToast();
    return response;
}

/**
 * 返回失败结果处理
 * @param error
 */
const loadResponseError = (error) => {
    if (typeof error.response === "undefined") {
        toast.message = RESPONSE_ERR_TEXT;
        toast.icon = "";
        return;
        // return store.commit("login/SET_LOGINFLAG", false);
    } else if (error && error.response) {
        return;
    } else {
        error.message = CONNECT_FAIL_TEXT;
        Promise.reject(error.message);
    }
}

let requestInterceptor;
let responseInterceptor;
export default {
    install: (axios) => {
        requestInterceptor = axios.interceptors.request.use(loadRequestSuccess, loadRequestError);
        responseInterceptor = axios.interceptors.response.use(loadResponseSuccess, loadResponseError);
    },
    uninstall: (axios) => {
        if (requestInterceptor) {
            axios.interceptors.request.eject(requestInterceptor);
        }
        if (responseInterceptor) {
            axios.interceptors.response.eject(responseInterceptor);
        }
    }
}
